package com.xyw.code.gateway.web.routes;

import com.xyw.code.gateway.web.service.IRouteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Component
@Slf4j
/**
 * 自定义路由表
 */
public class RedisRouteDefinitionRepository implements RouteDefinitionRepository  {

    @Autowired
    private IRouteService routeService;


    @Override
    public Flux<RouteDefinition> getRouteDefinitions() {
        //每次请求都会去读取这个加载动态路由对象的类
        //因此如果动态路由修改只需要修改这个动态加载类读取到的东西即可
        //this.applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this)); 这个方法刷新是用来刷新它默认实现的时候  用cached时候
        //这个方法唯一要求就是要快
        return  Flux.fromIterable(routeService.getRouteDefinitions());
    }

    @Override
    public Mono<Void> save(Mono<RouteDefinition> route) {
        return route.flatMap(routeDefinition -> {
            routeService.save(routeDefinition);
            return Mono.empty();
        });
    }

    @Override
    public Mono<Void> delete(Mono<String> routeId) {
        return routeId.flatMap(id -> {
            routeService.delete(id);
            return Mono.empty();
        });
    }
}
